package team.gl.nio.isncln;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;

import java.awt.Color;
import java.util.Timer;
import java.util.TimerTask;

import com.richman.controller.DecreaseRatioClient;

import team.gl.nio.cmn.Bag;
import team.gl.nio.cmn.BagDecoder;
import team.gl.nio.cmn.BagEncoder;
import team.gl.nio.cmn.ISNBag;
import team.gl.nio.cmn.ISNBagDecoder;
import team.gl.nio.cmn.ISNBagEncoder;
import team.gl.nio.cmn.NewBag;
import team.gl.nio.cmn.NewBagDecoder;
import team.gl.nio.cmn.NewBagEncoder;

public class ISNNettyClient {    
    public static String HOST = "127.0.0.1";
    public static int PORT = 9874;  

    public static Bootstrap bootstrap = getBootstrap();  
    
    public static EventLoopGroup group = null;
    
    public static Channel channel = null;


    /** 
     * ��ʼ��Bootstrap 
     * @return 
     */  
    public static final Bootstrap getBootstrap(){ 
    	if(group == null) {
    		group = new NioEventLoopGroup();
    	}
        Bootstrap b = new Bootstrap();  
        b.group(group).channel(NioSocketChannel.class);  

            b.handler(new ChannelInitializer<Channel>() {  
                @Override  
                protected void initChannel(Channel ch) throws Exception {  
                    ChannelPipeline pipeline = ch.pipeline();  
                    pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));  
                    pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));  
                    pipeline.addLast("decoder", new ISNBagDecoder());  
                    pipeline.addLast("encoder", new ISNBagEncoder());  
                    pipeline.addLast(new IdleStateHandler(0, 5, 0));  
                    pipeline.addLast("handler", new ISNClientHandler());  
                }  
            });  
        

        b.option(ChannelOption.SO_KEEPALIVE, true);  
        return b;  
    } 
    
    public static boolean connect(){  
    	
    	channel = getChannel(HOST,PORT);  
    	
    	if(channel == null){
    		return false;
    	}else{
    		TimerTask task = new TimerTask() {   
    			public void run() {   
    			}   
    			};   
    			  
    		new Timer(true).schedule(
    			new TimerTask() {
	    			public void run() {
	    				try {
	    					sendBagRequest(new ISNBag("xajh"));
	    				} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
	    			}   
	    		}
    			, 1000, 2000); 	  
    		return true;
    	}
    }

    public static final Channel getChannel(String host,int port){  
        Channel channel = null;  
        bootstrap = getBootstrap();
        try {  
            channel = bootstrap.connect(host, port).sync().channel();  
            System.out.println("connected");
        } catch (Exception e) {   
            return null;  
        }  
        return channel;  
    }  


    
    public static void sendBagRequest(ISNBag Bag) throws Exception {  
        // System.out.println(channel);
         if(channel!=null){  
         		channel.writeAndFlush(Bag).sync();
         		
         }else{  
             System.out.println("消息发送失败,连接尚未建立!!");             
             DecreaseRatioClient.mainWnd.updateMainWndStatusText(0, "与服务器连接已经断开");
         }  
     }  

/*    public static void main(String[] args) throws Exception {  
        try {      	
            NettyClient.sendRequest(new Bag("request")); 
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  */
} 
